/*
 * @Author: Qimu
 * @Date: 2020-04-22 22:39:04
 * @LastEditors: Qimu
 * @LastEditTime: 2020-09-19 20:20:42
 * @Description: file content
 * @FilePath: \vue-admin-koa2\vue-admin\src\request\http.js
 */
// import Vue from 'vue';
import axios from 'axios';
// import VueAxios from 'vue-axios';
// import api from '@/request/api/index';// 请求方法封装
import router from '@/router';
import utils from '@/plugins/utils'
import qs from 'qs';
import store from '@/store';
import { baseUrl } from '@/config';

// Vue.use(VueAxios, axios)
// Vue.prototype.$ajax = axios
// Vue.prototype.$qs = qs

// 创建axios实例    
const instance = axios.create({
  baseURL: baseUrl,
  timeout: 10000, // 超时
});
// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = `Bearer ${utils.local.get('userToken')}`
    if (token) config.headers.Authorization = token;
    if (config.method === 'post' && config.data !== undefined) {
      config.data = qs.stringify(config.data.params);
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });

instance.interceptors.response.use(res => {
  const { status } = res.data.meta
  if (status === 200 || status === 500) {
    return Promise.resolve(res);
  } else if (status === 401) {
    router.push({ path: '/login' }) //登录成功跳转到首页
    return Promise.resolve(res);
  } else {
    return Promise.reject(res);
  }
}, error => {
  return Promise.reject(error)
})

export default instance;
